package com.express.service;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import com.express.basic.constant.ExpressConstant;
import com.express.basic.exception.ExpressException;
import com.express.basic.util.MD5Util;
import com.express.dao.pojo.BizUser;
import com.express.dao.pojo.BizUserExample;
import com.express.param.AddUserReq;
import com.express.param.LoginUserReq;

@Service
public class BizUserService extends BaseService<BizUser, BizUserExample>{

	public BizUser login(LoginUserReq req){
		BizUserExample example = new BizUserExample();
		
		example.createCriteria().andUserNameEqualTo(req.getUserName())
					.andPasswordEqualTo(MD5Util.encode(req.getPassword()+ExpressConstant.salt))
					.andFlagEqualTo(1);		
		List<BizUser> bizUsers = selectByExample(example);
		return bizUsers.stream().findFirst()
					   .orElseThrow(() -> new ExpressException("201", "用户名密码不匹配"));
			
		
		
		
	}
	
	public BizUser register(AddUserReq req){
		BizUserExample example = new BizUserExample();
		example.createCriteria().andUserNameEqualTo(req.getUserName());
		
		Optional.ofNullable(selectByExample(example))
				.orElseThrow(()->new ExpressException("201", "用户名已存在"));
		
		BizUser bizUser = Optional.of(req).map((value) -> {
			BizUser temp = new BizUser();
			try {
				BeanUtils.copyProperties(temp, req);
				temp.setPassword(MD5Util.encode(req.getPassword() + ExpressConstant.salt));
				temp.setCreateDate(new Date());
			} catch (IllegalAccessException | InvocationTargetException e) {
			}
			return temp;
		}).get();
		
		insertSelective(bizUser);
		return bizUser;
		
		
	}
	
	
	
}
